<?php

namespace app\api\controller;

use app\api\model\Common;
use app\BaseController;
use frame\lib\Db;
use frame\lib\VerfiyParam;

class Login extends BaseController
{
    public function doLog()
    {
        if(!empty($_SESSION['api'])) error('无需重复登录哈 !');
        $param = $_POST;
        $conf = Common::verifyConf($param);
        if($conf['is_log'] != 1) error('当前App已关闭登录');
        $rule = ['username|用户名' => 'require', 'password|密码' => 'require'];
        VerfiyParam::init($param, $rule);
        $username = $param['username'];
        $password = $param['password'];
        $data = Db::name('user')->where(['username' => $username, 'role' => 2 , 'user_id' => $param['user_id'],'delete_time' => 0])->find();
        if (!$data) error('找不到该用户数据');
        if (encrypt_pwd($password) != $data['password']) error('账号或密码错误');
        if ($data['status'] == 2) error('该账户已被封禁');
        $cook = ['username' => $username, 'id' => $data['id'], 'user_id' => $data['user_id']];
        $_SESSION['api'] = $cook;
        // 登录时间保留7天
        setcookie(session_name(), session_id(), time() + 3600 * 24 * 7, '/');
        Common::statistics($data['user_id'] ,2);
        // 每天登录送金币
        $score = $data['score'];
        if($conf['log_send_score'] > 0 && date('d',getTime(3 , $data['last_login_time'])) != date('d' , time())){
            $score = $data['score'] + $conf['log_send_score'];
        }
        Db::name('user')->where(['id' => $data['id']])->update(['last_login_time' => getTime() , 'score' => $score]);
        success();
    }
    public function logOut()
    {
        if (@$_SESSION['api']) {
            $_SESSION['api'] = null;
            unset($_SESSION['api']);
            success();
        }
    }
}
